package third

import (
	"time"
	"fmt"
	"net/http"
	"io/ioutil"
	"encoding/json"
	"errors"
	// "strconv"
)
// facebook 相关接口
const (
	FB_JSURL 	= "https://graph.facebook.com/me?access_token=%s" 		// 获取玩家信息
	FB_ICON 	= "https://graph.facebook.com/%s/picture?type=large" 	// 玩家头像 url
)

type FbUserInfo struct {
	Id 		string
	Name 	string
	Icon 	string
}

// 获取 fb 玩家信息，获取成功则表示登录有效
func GetFbUserInfo(accessToken string) (*FbUserInfo, error) {
	url := fmt.Sprintf(FB_JSURL, accessToken)
	return GetFbUserInfoWithUrl(url)
}

func GetFbUserInfoWithUrl(url string) (*FbUserInfo, error) {
	// 使用超时连接
	client := http.Client{ Timeout: time.Second * 20 }
	resp, err := client.Get(url)
	if nil != err {
		return nil, err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if nil != err {
		return nil, err
	}
	var result map[string]interface{}
	err = json.Unmarshal([]byte(body), &result)
	if err != nil {
		return nil, err
	}
	if _, ok := result["error"]; ok {
		return nil, errors.New(string(body))
	}
	name, ok := result["name"]
	if !ok {
		return nil, errors.New("no name")
	}
	id, ok := result["id"]
	if !ok {
		return nil, errors.New("no id")
	}
	return &FbUserInfo{id.(string), name.(string), GetFbUserIcon(id.(string))}, nil
}

func GetFbUserIcon(userId string) string {
	return fmt.Sprintf(FB_ICON, userId)
}